<template>
  <div class="app-container">
    <el-form :model="form" ref="queryForm" size="mini">
      <el-row :gutter="10">
        <!--选择LLM-->
        <el-col :span="4">
          <el-form-item label="LLM" prop="LLM">
            <el-select
              v-model="form.config.llmModel"
              placeholder="Select LLM"
              size="mini"
              clearable
            >
              <el-option
                v-for="dict in dict.type.llm_model"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--选择Prompt Type-->
        <el-col :span="4">
          <el-form-item
            label="PromptType"
            prop="PromptType"
            label-width="90px"
          >
            <el-select
              v-model="form.config.promptType"
              placeholder="Select Prompt"
              size="mini"
              clearable
            >
              <el-option
                v-for="dict in dict.type.prompt_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="4">
            <el-form-item  label="Ade Filter"
            prop="adeFilter"> 
                <input type="checkbox" id="checkbox" v-model="form.config.afterFilter">
            </el-form-item>
        </el-col>

        <!--相似性-->

        <!--随机病例-->
        <el-col :span="5" style="justify-content: right; display: flex">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-refresh"
            @click="randomEmr"
            :loading="nexting"
            >Random EMR</el-button
          >
        </el-col>
        <!--选择Prompt Type-->
        <el-col :span="3" style="justify-content: right; display: flex">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="recognizeADE"
            :loading="loading"
            >ADE Recognition</el-button
          >
        </el-col>

        <!--保存为Case-->
        <el-col :span="3" style="justify-content: right; display: flex">
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-position"
            @click="openSaveCase"
            >Report Case</el-button
          >
        </el-col>
      </el-row>

      <!--RAG 模式下 知识库检索相关配置-->
      <el-row :gutter="10" v-if="form.config.promptType === 'RAG'">
        <el-form-item label="Retrieve">
          <el-select
            v-model="form.config.retriveConfig.collection"
            placeholder="Select ADE Knowledge"
            size="mini"
            clearable
            style="width: 200px; margin-left: 10px"
          >
            <el-option
              v-for="dict in dict.type.ade_knowledge"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>

          <el-select
            v-model="form.config.retriveConfig.chunkType"
            placeholder="Select Chunk Type"
            size="mini"
            clearable
            style="width: 150px; margin-left: 10px"
          >
            <el-option
              v-for="dict in dict.type.chunk_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>

          <el-input
            v-model="form.config.retriveConfig.simScoreThreshold"
            placeholder="Sim Threshold"
            size="mini"
            style="width: 120px; margin-left: 10px"
          />

          <el-input
            v-model="form.config.retriveConfig.topN"
            placeholder="TopN"
            size="mini"
            style="width: 120px; margin-left: 10px"
          />
        </el-form-item>
      </el-row>

      <el-row :gutter="10">
        <!-- 病历内容 -->
        <el-col :span="24">
          <el-form-item label="EMR Content" prop="emr">
            <el-input
              v-model="form.emr"
              rows="8"
              type="textarea"
              placeholder="Please enter the progress note (or course of treatment record)."
            />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="text-center">
        <h3 class="gradient-heading">ADE Recognization Results</h3>
      </div>

      <el-row>
        <el-form-item label="EMR Content" prop="emr">
          <br />
          <div
            v-html="formatEmr"
            style="
              line-height: 21px;
              font-family: monospace;
              font-size: 13px;
              border: 1px solid #ccc;
              padding: 10px;
            "
          ></div>
        </el-form-item>
      </el-row>

      <el-row :gutter="20">
        <!-- 识别的药物不良反应事件 -->
        <el-col :span="12">
          <el-form-item label="ADEs" prop="ades">
            <el-input
              v-model="jsonText"
              rows="17"
              type="textarea"
              placeholder=""
              @input="onJsonChange"
            />

            <div class="json-status mt-2">
              <el-tag
                :type="jsonValid ? 'success' : 'danger'"
                effect="plain"
                size="mini"
              >
                {{ jsonStatusText }}
              </el-tag>
            </div>
          </el-form-item>
        </el-col>

        <!-- 请求的Prompt -->
        <el-col :span="12">
          <el-form-item label="Prompt" prop="prompt">
            <br />
            <pre
              style="
                line-height: 21px;
                font-size: 13px;
                white-space: pre-wrap;
                border: 1px solid #ccc;
                padding: 10px;
                margin-top: 0px;
                height: 320px;
                overflow-y: auto;
              "
              >{{ prompt }}</pre
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 添加或修改Ade Cases对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="75%" append-to-body>
      <el-form ref="caseform" :model="caseForm" :rules="rules">
        <el-form-item label="Content" prop="content">
          <el-input
            v-model="caseForm.content"
            type="textarea"
            rows="5"
            placeholder="Pls input content"
          />
        </el-form-item>
        <el-form-item label="Ades" prop="ades">
          <el-input
            v-model="caseForm.ades"
            type="textarea"
            rows="5"
            placeholder="Pls input ades(json format)"
          />
        </el-form-item>
        <el-form-item label="LLM" prop="llm">
          <el-select v-model="caseForm.llm" placeholder="Select LLM">
            <el-option
              v-for="dict in dict.type.llm_model"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="PromptType" prop="promptType">
          <el-select
            v-model="caseForm.promptType"
            placeholder="Select PromptType"
          >
            <el-option
              v-for="dict in dict.type.prompt_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Case Type" prop="type">
          <el-select v-model="caseForm.type" placeholder="Select Case Type">
            <el-option
              v-for="dict in dict.type.ade_case_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Description" prop="description">
          <el-input
            v-model="caseForm.description"
            type="textarea"
            rows="5"
            placeholder="Pls input description"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCaseForm">Confirm</el-button>
        <el-button @click="cancel">Cancel</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { recognize } from "@/api/ade/adeRecognition";
import { randomStandard } from "@/api/ade/standard";
import { addCase } from "@/api/ade/case";

export default {
  name: "AdeApp",
  dicts: [
    "llm_model",
    "prompt_type",
    "ade_knowledge",
    "chunk_type",
    "ade_case_type",
  ],
  data() {
    return {
      //ADE请求体
      form: {
        emr: "", // 病历内容
        config: {
          llmModel: "ernie-3.5-8k", // LLM模型
          promptType: "SAG", // Prompt类型
          afterFilter: true, // 是否启用后处理
          // RAG 模式下的检索配置
          retriveConfig: {
            // 检索配置
            collection: "adeknowledge_repeat_filter", // 知识库集合  adeknowledge_repeat_filter
            chunkType: "mark", // 分块类型
            simScoreThreshold: 0.6, // 相似度阈值
            topN: 5, // 返回的相似文档数量
          },
          // rerankConfig:{ // 重排序配置
          //     reScoreThreshold: 0.6,   // 重排序阈值
          //     topN: 5,                 // 重排序后返回的文档数量
          // }
        },
      },

      //ADE Case 表单
      caseForm: {},
      title: "", //对话框名称
      open: false, //是否显示对话框
      // 表单校验
      rules: {
        content: [
          {
            required: true,
            message: "Content can not be empty!",
            trigger: "blur",
          },
        ],
        ades: [
          {
            required: true,
            message: "Ades can not be empty!",
            trigger: "blur",
          },
        ],
        llm: [
          {
            required: true,
            message: "LLM can not be empty!",
            trigger: "change",
          },
        ],
        promptType: [
          {
            required: true,
            message: "PromptType can not be empty!",
            trigger: "change",
          },
        ],
        type: [
          {
            required: true,
            message: "Case Type can not be empty!",
            trigger: "change",
          },
        ],
        description: [
          {
            required: true,
            message: "Description can not be empty!",
            trigger: "blur",
          },
        ],
      },

      // JSON数据
      jsonText: "",
      originalJsonText: "",
      jsonValid: true,
      jsonStatusText: "JSON Format Correct",

      //识别后的EMR
      formatEmr: "",
      // 请求的Prompt
      prompt: "",

      // 状态
      loading: false,
      nexting: false,
    };
  },
  computed: {},
  created() {
    // 初始化JSON文本
    // this.resetJson();
    this.randomEmr();
  },
  methods: {
    // 随机病例
    randomEmr() {
      this.nexting = true;
      var data = { status: "", source: "" };
      randomStandard(data)
        .then((response) => {
          if (response.data == null || response.data == undefined) {
            this.$message.warning(
              "No aviliable emr data, please change the source or status!"
            );
            this.nexting = false;
            return;
          }
          this.form.emr = response.data.content;
          this.nexting = false;

          //成功获取到数据 要将前一个数据的ADE结果清空
          this.formatEmr='';
          this.jsonText='';
          this.prompt = '';
        })
        .catch((error) => {
          this.$message.error("Too fast, please wait a moment!");
          this.nexting = false;
        });
    },
    //ADE是额
    recognizeADE() {
      this.loading = true;
      recognize(this.form)
        .then((response) => {
          this.jsonText = JSON.stringify(response.data.ades, null, 2);
          this.originalJsonText = this.jsonText; // 保存原始JSON文本
          this.jsonValid = true;
          this.jsonStatusText = "JSON Format Correct!";

          // 设置请求的Prompt
          this.prompt = response.data.prompt || "No prompt provided";

          // 格式化EMR内容，突出显示识别出的ADE
          let rep = "";
          this.formatEmr = this.form.emr; // 初始化格式化的EMR内容
          for (let i = 0; i < response.data.ades.length; i++) {
            rep = response.data.ades[i].sentence; // 将其他ADE名称用 | 分隔
            this.formatEmr = this.formatEmr.replaceAll(
              rep,
              '<font color="red">' + rep + "</font>"
            );
          }
          this.loading = false;
        })
        .catch((error) => {
          console.error("Error recognizing ADE:", error);
          this.$message.error("Failed to recognize ADE");
          this.loading = false;
          this.jsonText = "";
        });
    },
    // 重置JSON数据
    resetJson() {
      this.jsonText = this.originalJsonText;
      this.jsonValid = true;
      this.jsonStatusText = "JSON Format Correct!";
    },
    // 格式化JSON
    formatJson() {
      try {
        const parsed = JSON.parse(this.jsonText);
        this.jsonText = JSON.stringify(parsed, null, 2);
        this.jsonValid = true;
        this.jsonStatusText = "JSON Format Correct!";
      } catch (error) {
        this.jsonValid = false;
        this.jsonStatusText = `Wrong Format: ${error.message}`;
        this.$message.error("JSON Format Wrong，Can not be formatted!");
      }
    },
    // 验证JSON
    validateJson() {
      try {
        JSON.parse(this.jsonText);
        this.jsonValid = true;
        this.jsonStatusText = "JSON Foramat Correct";
        // this.$message.success('JSON格式验证通过');
      } catch (error) {
        this.jsonValid = false;
        this.jsonStatusText = `Wrong Format: ${error.message}`;
        this.$message.error("Wrong JSON Format");
      }
    },

    // JSON内容变化时自动验证
    onJsonChange() {
      try {
        JSON.parse(this.jsonText);
        this.jsonValid = true;
        this.jsonStatusText = "JSON Format Correct!";
      } catch (error) {
        this.jsonValid = false;
        this.jsonStatusText = `Wrong Format: ${error.message}`;
      }
    },

    //=============================================新增案例=========================
    // 取消按钮
    cancel() {
      this.open = false;
      this.caseForm = {};
      this.resetForm("caseform");
    },
    //打开保存case对话框
    openSaveCase() {
      this.cancel();
      this.title = "Save Case";
      this.caseForm.content = this.form.emr;
      this.caseForm.ades = this.jsonText;
      this.caseForm.llm = this.form.config.llmModel;
      this.caseForm.promptType = this.form.config.promptType;
      this.caseForm.source = "ADE Recognition";
      this.open = true;
    },
    /** 提交按钮 */
    submitCaseForm() {
      this.$refs["caseform"].validate((valid) => {
        if (valid) {
          addCase(this.caseForm).then((response) => {
            this.$modal.msgSuccess("Report Case Successfully!");
            this.open = false;
          });
        }
      });
    },
  },
};
</script>

<style>
.gradient-heading {
  text-align: center;
  /* 水平居中 */
  color: #2c3e50;
  /* 深蓝色文字 */
  font-size: 20px;
  /* 字体大小 */
  margin-bottom: 20px;
  /* 底部外边距 */
  padding-bottom: 10px;
  /* 底部内边距（可选） */
  border-bottom: 2px solid #3498db;
  /* 底部边框（可选） */
}
</style>